package com.marver.login.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.marver.beans.request.GetTokenReq;
import com.marver.beans.request.LoginReq;
import com.marver.beans.response.AccessToken;
import com.marver.common.annotation.AccessNum;
import com.marver.common.annotation.TokenFilter;
import com.marver.common.result.Result;
import com.marver.common.result.ResultStatus;
import com.marver.common.utils.*;
import com.marver.entity.qo.Param;
import com.marver.login.service.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/oauth/")
public class LoginController {
	
	private Logger logger =LoggerFactory.getLogger(this.getClass());
    @Autowired  
    private LoginService loginService;
    
    /**
     * 获取token
     * @param request
     * @param response
     * @param qo
     * @return
     * @throws JsonProcessingException
     * @throws IOException
     */
    @PostMapping(value="/login")
    @TokenFilter()
    public Result getAccessTokenByAdmin(HttpServletRequest request, HttpServletResponse response, @RequestBody @Valid LoginReq qo, BindingResult result) throws JsonProcessingException, IOException
    {
        if(result.hasErrors()){
            return Result.validation(ResultStatus.INVALID_PARAM.getErrorCode(),result);
        }
    	String loginTelNum=qo!=null?qo.getUserNum():"";
    	logger.info(DateUtils.getCurrDateTime()+":"+loginTelNum+"请求登录");
        Result resultMsg;
        if(qo==null){
        	resultMsg=new Result(ResultStatus.INVALID_PARAM.getErrorCode()); 
        }else{
        	resultMsg=loginService.getLoginToken(qo,HttpsUtil.getIpAddr(request),true);
            if(resultMsg.getCode()==ResultStatus.SUCCESS.getErrorCode()&&!StringUtils.isEmpty(resultMsg.getData())){
            	AccessToken accessToken=(AccessToken)((List)resultMsg.getData()).get(0);
            	Cookie cookie=new Cookie("access_token",accessToken.getAccessToken());
            	cookie.setPath("/");
                response.addCookie(cookie);
                Cookie cookie1=new Cookie("expires_in",String.valueOf(accessToken.getExpiresIn()));
                cookie1.setPath("/");
                response.addCookie(cookie1);
                Cookie cookie2=new Cookie("token_type",accessToken.getTokenType());
                cookie2.setPath("/");
                response.addCookie(cookie2);
            }
            
        }
        if(resultMsg.getCode()==0){
        	logger.info(DateUtils.getCurrDateTime()+":"+loginTelNum+"登录成功");
        }else{
        	logger.info(DateUtils.getCurrDateTime()+":"+loginTelNum+"登录失败，原因："+resultMsg.getMsg());
        }
        return resultMsg;
    }    

    
    /**
     * 获取图片验证码
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "getcaptcha")
    @TokenFilter()
    public Result getCaptcha(HttpServletRequest request,HttpServletResponse response) throws IOException  
    { 
        int captchaExpires = 10*60; //超时时间10min 
        int captchaW = 100;  
        int captchaH = 30; 
        String uuid = UUID.randomUUID().toString(); 
        //生成随机字串 
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4); 
        
        //将验证码以<key,value>形式缓存到redis  
        JedisUtils.set(uuid, verifyCode, captchaExpires);
        logger.info("uuid="+uuid+",code="+verifyCode); 
	      
       String base64Img =VerifyCodeUtils.outputImage(captchaW, captchaH, verifyCode);
       List<Map<String,String>> list=new ArrayList<Map<String,String>>();
       Map<String,String> map=new HashMap<String,String>();
       map.put("captcha_code", uuid);
       map.put("captcha_img", base64Img);
       list.add(map);
       return new Result(ResultStatus.SUCCESS.getErrorCode(),list);
    }

    /**
     * 获取token
     * @param qo
     * @return
     * @throws JsonProcessingException
     * @throws IOException
     */
    @PostMapping("/token")
    @AccessNum(minVisitsNum = 5,dayVisitsNum = 2000)
    @TokenFilter()
    public Result getAccessToken(HttpServletRequest request, @RequestBody Param<GetTokenReq> qo) throws JsonProcessingException, IOException{
        Result resultMsg = new Result() ;
        if(StringUtils.isEmpty(qo.getBody())){
            return new Result(ResultStatus.INVALID_PARAM.getErrorCode());
        }
        ValidDataUtil.checkData(qo.getBody().getAppId(),"required","appId",resultMsg);
        ValidDataUtil.checkData(qo.getBody().getAuthCode(),"required","authCode",resultMsg);
        ValidDataUtil.checkData(qo.getBody().getCustId(),"required","custId",resultMsg);
        if(resultMsg.getCode()==ResultStatus.INVALID_PARAM.getErrorCode()){
            return resultMsg;
        }

        resultMsg = loginService.getAccessToken(qo.getBody(),HttpsUtil.getIpAddr(request));
        return resultMsg;
    }
}

